package com.codeanalysissys.backend.service.core.impl;

import com.codeanalysissys.backend.API;
import com.codeanalysissys.backend.entity.Analysis;
import com.codeanalysissys.backend.entity.Language;
import com.codeanalysissys.backend.entity.response.ResponseCode;
import com.codeanalysissys.backend.entity.response.Result;
import com.codeanalysissys.backend.service.core.CodeAnalysisService;
import com.codeanalysissys.backend.utils.AnalysisArgsBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;

@Service
public class CodeAnalysisServiceImpl implements CodeAnalysisService {
    @Autowired
    AnalysisArgsBuilder analysisArgsBuilder;

    @Override
    public Result analysis(String content, Analysis analysis, Language language) {
        // 将字符串转换为字节数组
        byte[] bytes = content.getBytes();
        // 使用 ByteArrayInputStream 封装字节数组为输入流
        InputStream contentStream = new ByteArrayInputStream(bytes);

        ArrayList<Analysis> opt = new ArrayList<>();
        opt.add(analysis);

//        // 封装API对象，使用AnalysisArgsBuilder
//        ArrayList<String> graph = new API(analysisArgsBuilder
//                .setInputStream(contentStream)
//                .setAnalysisOpt(opt)
//                .setLanguageType(language).build()).getExec().executeWithContent();
//
//        // 根据生成图是否为空返回结果
//        if (graph != null) {
//            return new Result.Builder(ResponseCode.ANALYSIS_SUCCESS).data(graph).build();
//        } else {
//            return new Result.Builder(ResponseCode.ANALYSIS_FAIL).build();
//        }
        return null;
    }

    @Override
    public Result analysisAll(String content, Language language) {
        byte[] bytes = content.getBytes();

        ArrayList<Analysis> opt = (ArrayList<Analysis>) Arrays.stream(Analysis.values())
                .filter(analysis -> analysis.getType() < 4)
                .collect(Collectors.toList());

        // 封装API对象，使用AnalysisArgsBuilder
        ArrayList<String> graph = new API(analysisArgsBuilder
                .setAnalysisOpt(opt)
                .setLanguageType(language).build()).getExec().executeWithContent(bytes);

        // 根据生成图是否为空返回结果
        if (graph != null) {
            return new Result.Builder(ResponseCode.ANALYSIS_SUCCESS).data(graph).build();
        } else {
            return new Result.Builder(ResponseCode.ANALYSIS_FAIL).build();
        }
    }
}
